﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Aspose.Cells;
using System.IO;


namespace Mall.Infrastructure.Excel
{
    public static class AsposeCells
    {
        /// <summary>
        /// 根据Datable获取Excel
        /// </summary>
        /// <param name="source">源数据</param>
        /// <param name="dictionary">数据字典</param>
        /// <param name="sourcePath">模板源文件</param>
        public static byte[] GetExcel(DataTable source, Dictionary<string, string> dictionary, string sourcePath)
        {
            WorkbookDesigner designer = new WorkbookDesigner();
            if (!System.IO.File.Exists(sourcePath))
            {
                throw new Exception(string.Format("{0}:源文件不存在", sourcePath));
            }
            else
            {
                designer.Open(sourcePath);
                //数据源 
                designer.SetDataSource(source);
                //额外数据
                foreach (var item in dictionary)
                {
                    designer.SetDataSource(item.Key, item.Value);
                }
                designer.Process();
                System.IO.MemoryStream ms = designer.Workbook.SaveToStream();//生成数据流 
                byte[] bt = ms.ToArray();

                return bt;
            }
        }

        /// <summary>
        /// 根据List获取Excel
        /// </summary>
        /// <param name="source">源数据</param>
        /// <param name="dictionary">数据字典</param>
        /// <param name="sourcePath">模板源文件</param>
        public static byte[] GetExcel<T>(List<T> entitys,string tableName, Dictionary<string, string> dictionary, string sourcePath)
        {
            var source = DataTableExtend.ListToDataTable<T>(entitys, tableName);
            WorkbookDesigner designer = new WorkbookDesigner();
            //!System.IO.File.Exists(sourcePath)


            if (false)
            {
                throw new Exception(string.Format("{0}:源文件不存在", sourcePath));
            }
            else
            {
                designer.Open(sourcePath);
                //数据源 
                designer.SetDataSource(source);
                //额外数据
                foreach (var item in dictionary)
                {
                    designer.SetDataSource(item.Key, item.Value);
                }
                designer.Process();
                System.IO.MemoryStream ms = designer.Workbook.SaveToStream();//生成数据流 
                byte[] bt = ms.ToArray();

                return bt;
            }
        }
    }
}
